package utils.weixin;

import Model.Userwx;
import Dao.UserwxMapper;
import utils.ReturnData;
import utils.TextUtils;
import utils.http.HttpRequest;

import javax.servlet.ServletContext;

/**
 * 下载微信头像并保存到本地
 */
public class WxAvatarDownloadThread extends Thread{

    private UserwxMapper userwxMapper;
    private ServletContext servletContext;
    private String avatarUrl;
    private Long userwxId;

    private WxAvatarDownloadThread(){

    }

    public WxAvatarDownloadThread(UserwxMapper userwxMapper,ServletContext servletContext,String avatarUrl,Long userwxId){
        this.userwxMapper = userwxMapper;
        this.servletContext = servletContext;
        this.avatarUrl = avatarUrl;
        this.userwxId = userwxId;
    }

    @Override
    public void run(){
        super.run();
        //没有用户头像就不再走下面的方法了
        if(TextUtils.isEmpty(avatarUrl)){
            return;
        }
        int index = avatarUrl.lastIndexOf("/");
        avatarUrl = avatarUrl.substring(0,index+1)+ConstantUtils.AVATAR_640;    //640*640的头像
        ReturnData returnData = HttpRequest.downloadSingleFile(servletContext,avatarUrl);
        if(returnData.getCode()==ReturnData.KEY_CODE_SUCCESS){
            //更新用户头像
            Userwx userwx = new Userwx();
            userwx.setId(userwxId);
            userwx.setAvatarUrl(returnData.getMsg());
            userwxMapper.updateUserAvatarAndFlag(userwx);
        }
    }
}
